package com.android.supermarket.helper

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.*
import android.os.Parcelable
import android.util.Log

/**
 * Created by pengtaoH on 2018/7/19.
 */


class UsbHelper(context: Context) {

    private val mUsbManager: UsbManager
    private var mDevice: UsbDevice? = null
    private var mConnection: UsbDeviceConnection? = null
    private var mEndpointIntr: UsbEndpoint? = null
    private val mUsbReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (ACTION_USB_PERMISSION == action) {
                synchronized(this) {
                    val device = intent.getParcelableExtra<Parcelable>(UsbManager.EXTRA_DEVICE) as UsbDevice
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (device != null) {
                            setDevice(device)
                        } else {
                            Closeusb()
                            mDevice = device
                        }
                    } else {
                        Log.d(TAG, "permission denied for device $device")
                    }

                }

            }
        }
    }

    @SuppressLint("NewApi")
    private fun setDevice(device: UsbDevice?) {
        if (device != null) {
            var intf: UsbInterface? = null
            var ep: UsbEndpoint? = null

            val InterfaceCount = device.interfaceCount
            var j: Int

            mDevice = device
            j = 0
            while (j < InterfaceCount) {
                var i: Int

                intf = device.getInterface(j)
                Log.i(TAG, "接口是:" + j + "类是:" + intf!!.interfaceClass)
                if (intf.interfaceClass == 7) {
                    val UsbEndpointCount = intf.endpointCount
                    i = 0
                    while (i < UsbEndpointCount) {
                        ep = intf.getEndpoint(i)
                        Log.i(TAG, "端点是:" + i + "方向是:" + ep!!.direction + "类型是:" + ep.type)
                        if (ep.direction == 0 && ep.type == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                            Log.i(TAG, "接口是:" + j + "端点是:" + i)
                            break
                        }
                        i++
                    }
                    if (i != UsbEndpointCount) {
                        break
                    }
                }
                j++
            }
            if (j == InterfaceCount) {
                Log.i(TAG, "没有打印机接口")
                return
            }

            mEndpointIntr = ep
            if (device != null) {
                val connection = mUsbManager.openDevice(device)

                if (connection != null && connection.claimInterface(intf, true)) {
                    Log.i(TAG, "打开成功！ ")
                    mConnection = connection

                } else {
                    Log.i(TAG, "打开失败！ ")
                    mConnection = null
                }
            }
        } else {

        }
    }

    @SuppressLint("NewApi")
    fun Openusb() {
        if (mDevice != null) {
            setDevice(mDevice)
            if (mConnection == null) {
                val deviceList = mUsbManager.deviceList
                val deviceIterator = deviceList.values.iterator()

                while (deviceIterator.hasNext()) {
                    val device = deviceIterator.next()
                    mUsbManager.requestPermission(device, mPermissionIntent)
                }
            }
        } else {
            val deviceList = mUsbManager.deviceList
            val deviceIterator = deviceList.values.iterator()

            while (deviceIterator.hasNext()) {
                val device = deviceIterator.next()
                mUsbManager.requestPermission(device, mPermissionIntent)
            }
        }
    }

    @SuppressLint("NewApi")
    fun Closeusb() {
        if (mConnection != null) {
            mConnection!!.close()
            mConnection = null
        }
    }

    fun GetUsbStatus(Language: Boolean): String {
        if (mDevice == null) {
            return if (Language)
                "没有Usb设备！"
            else
                "No Usb Device!"
        }
        if (mConnection == null) {
            return if (Language)
                "Usb设备不是打印机！"
            else
                "Usb device is not a printer!"
        }
        return if (Language) "Usb打印机打开成功！" else "Usb Printer Open success！"
    }

    fun GetUsbStatus(): Boolean {
        return if (mConnection == null) false else true
    }

    @SuppressLint("NewApi")
    fun sendCommand(Content: ByteArray): Boolean {
        var result: Boolean = true
        synchronized(this) {
            var len = -1
            if (mConnection != null) {
                len = mConnection!!.bulkTransfer(mEndpointIntr, Content, Content.size, 10000)
            }

            if (len < 0) {
                result = false
                Log.i(TAG, "发送失败！ $len")
            } else {
                result = true
                Log.i(TAG, "发送" + len + "字节数据")
            }
        }
        return result
    }

    init {
        mUsbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
        mPermissionIntent = PendingIntent.getBroadcast(context, 0, Intent(ACTION_USB_PERMISSION), 0)
        val filter = IntentFilter(ACTION_USB_PERMISSION)
        context.registerReceiver(mUsbReceiver, filter)
    }

    companion object {
        private val TAG = "UsbAdmin"
        private var mPermissionIntent: PendingIntent? = null
        private val ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION"
    }
}